package com.demo.socket.anyFile;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSocketTask implements Runnable {
    private Socket s;

    public ServerSocketTask(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        String ip = s.getInetAddress().getHostAddress();
        System.out.println(ip);
        try {
            //获取客户端输入流
            InputStream in = s.getInputStream();
            //读取信息
            byte[] names = new byte[100];
            int len = in.read(names);
            String fileName = new String(names, 0, len);
            String[] fileNames = fileName.split("\\.");
            String fileLast = fileNames[fileNames.length - 1];
            //然后将后缀名发给客户端
            OutputStream out = s.getOutputStream();
            out.write(fileLast.getBytes());
            //新建文件
            File dir = new File("d:\\server\\" + ip);
            if (!dir.exists())
                dir.mkdirs();
            File file = new File(dir, fileNames[0] + "." + fileLast);
            FileOutputStream fos = new FileOutputStream(file);
            //将Socket输入流中的信息读入到文件
            byte[] bufIn = new byte[1024];
            while ((len = in.read(bufIn)) != -1) {
                //写入文件
                fos.write(bufIn, 0, len);
            }
            fos.close();
            s.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        /*
         * 服务端先接收客户端传过来的信息，然后向客户端发送接收成功，新建文件，接收客户端信息
         */
        //建立服务端
        ServerSocket ss = new ServerSocket(9000);//客户端端口需要与服务端一致
        while (true) {
            //获取客户端Socket
            Socket s = ss.accept();
            new Thread(new ServerSocketTask(s)).start();
        }
    }
}
